/* 专门处理数组 */

import observe from "./index";

const oldArrayProtoMethods = Array.prototype;
// 此 7 个方法能改变数组
const methods = [
  "push",
  "splice",
  "slice",
  "pop",
  "shift",
  "unshift",
  "reverse",
];
export const arrayMethods = Object.create(Array.prototype);

methods.forEach((method) => {
  // AOP 切片编程, 将7个方法重写，但不影响原来的方法
  arrayMethods[method] = function (...args) {
    log("数组改变----");
    // 如果新增的数据是对象格式，也需要被拦截 push, splice, unshift
    let inserted; // 新增的数据
    let ob = this.__ob__;
    switch (method) {
      case "push":
      case "unshift":
        inserted = args; // [2,4,5].unshift(9)  ==> [9,2,4,5]
        break;
      case "splice":
        inserted = args.slice(2); // [2,4,5,6].splice(2,1,9)  ==> [2,4,9,6]
        break;
      default:
        break;
    }

    // inserted 最后一定是个数组, 因为 args 是个数组
    if (inserted) ob.observeArray(inserted);
    ob.dep.notify();
    let result = oldArrayProtoMethods[method].call(this, ...args);
    return result;
  };
});
